<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\reportexcel;

use app\command\BaseWork;
use app\enum\ReportRecordEnum;
use app\model\report\ReportRecordListModel;
use app\service\BaseService;
use app\service\report\ReportRecordListService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class ReportRecordDataConsumerWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('v3_report_record_data_consumer_work');
        $this->setDescription('实时拉取报表消费者');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('实时拉取报表数据开始');
        $st = time() + (5 * 60);
        $redis = Cache::store('redis')->handler();
        $key = ReportRecordEnum::CACHE_KEY['report_data_fetch'];
        while (time() < $st) {
            $listId = intval($redis->lPop($key));
            if (! $listId) {
                usleep(500000);
                continue;
            }
            try {
                $this->getOutputMessage('实时拉取报表数据开始,报表id:' . $listId);
                ReportRecordListService::setStatus($listId, ReportRecordListModel::STATUS_WAIT_SYNC);
                if (! ReportRecordListService::getReportRecordContent($listId)) {
                    throw new \Exception(ReportRecordListService::getError(0));
                }
                ReportRecordListService::setStatus($listId, ReportRecordListModel::STATUS_SYNC);
                $this->getOutputMessage('实时拉取报表数据成功,报表id:' . $listId);
                $redis->rPush(ReportRecordEnum::CACHE_KEY['report_file_fetch'], $listId);
            } catch (\Exception $e) {
                ReportRecordListService::setStatus($listId, ReportRecordListModel::STATUS_NO);
                $redis->rPush(ReportRecordEnum::CACHE_KEY['report_data_fetch'], $listId);
                $this->getOutputMessage('实时拉取报表数据失败,报表id:' . $e->getMessage());
            }
        }
        $this->getOutputMessage('实时拉取报表数据结束');
    }
}
